import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const time = {
  JSON: 5000,
  BLOB: 15000
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 50000
})

// 请求拦截
service.interceptors.request.use(
  // resolve
  (config) => {
    // 添加 token 头
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  // reject
  (error) => {
    Message({
      type: 'error',
      message: error
    })
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    // 返回Blob对象
    if (response.data instanceof Blob) {
      service.timeout = time.BLOB
      return response.data
    }
    service.timeout = time.JSON
    const { data, message, success } = response.data
    if (success) {
      return data
    } else {
      Message({
        type: 'error',
        message: message
      })
      return Promise.reject(new Error(message))
    }
  },
  async(error) => {
    if (error.response.status === 401) {
      Message({
        type: 'warning',
        message: '登录已失效'
      })
      // Token 失效
      await store.dispatch('user/logOut')
      router.push('/login')
      return Promise.reject(error)
    }
    Message({
      type: 'error',
      message: error.message
    })
    return Promise.reject(error)
  }
)

export default service
